package com.atguigu.lease.web.app.service.impl;

import com.aliyun.dysmsapi20170525.Client;
import com.aliyun.dysmsapi20170525.models.SendSmsRequest;
import com.atguigu.lease.common.busiexception.BusiException;
import com.atguigu.lease.common.constant.RedisConstant;
import com.atguigu.lease.common.result.ResultCodeEnum;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.atguigu.lease.model.entity.UserInfo;
import com.atguigu.lease.web.app.service.UserInfoService;
import com.atguigu.lease.web.app.mapper.UserInfoMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.Random;
import java.util.concurrent.TimeUnit;

/**
 * @author liubo
 * @description 针对表【user_info(用户信息表)】的数据库操作Service实现
 * @createDate 2023-07-26 11:12:39
 */
@Service
public class UserInfoServiceImpl extends ServiceImpl<UserInfoMapper, UserInfo>
        implements UserInfoService {

    @Autowired
    private StringRedisTemplate stringRedisTemplate;
    @Autowired
    private Client client;

    @Autowired
    private UserInfoMapper userInfoMapper;

    private static final String KEY_PREFIX =  RedisConstant.APP_LOGIN_PREFIX;

    @Override
    public void getCode(String phone) {
//        判断手机号是否为空
        if (!StringUtils.hasText(phone)) {
            throw new BusiException(ResultCodeEnum.APP_LOGIN_PHONE_EMPTY);
        }

//        redis中获取验证码
        String redisCode = stringRedisTemplate.opsForValue().get(KEY_PREFIX + phone);
        if (redisCode != null) {
//            获取redis中的剩余时间
            Long expire = stringRedisTemplate.getExpire(KEY_PREFIX + phone, TimeUnit.SECONDS);
//            如果剩余时间 减去 档期那时间 小于 60s 就会抛出异常 发送太频繁
            Integer redisConstantTime = RedisConstant.APP_LOGIN_CODE_TTL_SEC;
            if (redisConstantTime - expire < RedisConstant.APP_LOGIN_CODE_RESEND_TIME_SEC) {
                throw new BusiException(ResultCodeEnum.APP_SEND_SMS_TOO_OFTEN);
            }
        }
//        发短信 = phone + code
        String code = createCode(6);
//      发送
        sendCode(phone, code);
//        验证码存进redis
        stringRedisTemplate.opsForValue().set(KEY_PREFIX + phone, code, RedisConstant.APP_LOGIN_CODE_TTL_SEC, TimeUnit.SECONDS);

    }

    public String createCode(Integer num) {
        StringBuffer stringBuffer = new StringBuffer();
        Random random = new Random();
        for (int i = 0; i < num; i++) {
            stringBuffer.append(random.nextInt(10));
        }
        return stringBuffer.toString();
    }

    public void sendCode(String phone, String code) {
        SendSmsRequest sendSmsRequest = new SendSmsRequest();
        sendSmsRequest.setSignName("阿里云短信测试")
                .setTemplateCode("SMS_154950909")
                .setPhoneNumbers(phone)
                .setTemplateParam("{\"code\":"+ "\"" + code + "\"" + "}");
        com.aliyun.teautil.models.RuntimeOptions runtime = new com.aliyun.teautil.models.RuntimeOptions();
        try{
            // 复制代码运行请自行打印 API 的返回值
            client.sendSmsWithOptions(sendSmsRequest, runtime);
        }
        catch (Exception e) {
            System.out.println(e.getMessage());
        }
    }
}




